package com.fw.kafka_chapter_1.concumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @Author:yanwei
 * @Date: 2020/8/16 - 17:48
 *
 * Kafka 消息指定位移消费
 */
@Slf4j
public class ConcumerOffset {

    public static void main(String[] args) {
        Properties properties = new Properties();
        // key 序列化器指定
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        // value 序列化执行
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
        // 指定组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"fw_group");
        // 指定连接
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.227.129:9092");
        //设置手动提交开启
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,Boolean.TRUE);
        //创建接收器
        KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(properties);


        // 指定 topic
        consumer.subscribe(Collections.singletonList("fw"));
        // timeout参数设置多少合适？太短会使分区分配失败，太长又有可能造成一些不必要的等待
        consumer.poll(Duration.ofMillis(2000));
        // 必须先执行该上方拿取消息过程，否则得不到分区位置
        Set<TopicPartition> assignment = consumer.assignment();
        for (TopicPartition topicPartition : assignment) {
            consumer.seek(topicPartition,1);
        }

      lastConcumer:{
            // 指定位移到尾部位置
            // 方式一
            Map<TopicPartition, Long> topicPartitionLongMap = consumer.endOffsets(assignment);
            for (TopicPartition topicPartition : assignment) {
                consumer.seek(topicPartition,topicPartitionLongMap.get(topicPartition));
            }
            // 方式二
            //consumer.seekToBeginning(assignment);
        }

        // 指定分区        第一个分区，第10个offset
       // consumer.seek(new TopicPartition("fw",0),0);
        while (true){
            // 10 毫秒获取一次
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(10));
            for (ConsumerRecord<String, String> stringStringConsumerRecord : poll) {
                System.err.println(stringStringConsumerRecord.value());
            }
        }
    }
}
